<script setup lang="ts">
import type { PlusColumn, FieldValues, OptionsRow } from "plus-pro-components";
import {
  PlusDialogForm,
  PlusCheckCardGroup,
  PlusDialogFormInstance
} from "plus-pro-components";
import { useColumns } from "./columns";
import {
  computed,
  Fragment,
  h,
  onMounted,
  reactive,
  ref,
  watch,
  nextTick
} from "vue";
import { ElScrollbar } from "element-plus";
import { IconifyIconOnline } from "@/components/ReIcon";
import { getWexinHomeRecommend, updateAppConfig } from "@/api/config";
import { HomeRecommendChildrenItem, HomeRecommendItem } from "types/app-config";
import { message } from "@/utils/message";
import { getFlowerOptions } from "@/api/flower";
import { ElTreeItem } from "types";

const SERVER_URL = import.meta.env.VITE_SERVER_URL;

const state = reactive({
  loading: false,
  submitting: false
});

const dataList = ref<HomeRecommendChildrenItem[]>();

const typeOptions = ref<OptionsRow[]>([]);

const flowerList = ref<{ title: string; value: number }[]>([]);
const flowerOptions = computed(() => {
  if (formData.value.type) {
    const child = rawData.find(item => item.id === formData.value.type);
    if (child) {
      const flowerIds = child.children.map(item => item.id);
      return flowerList.value.map(item => {
        if (flowerIds.includes(item.value)) {
          return { ...item, disabled: true };
        }
        return item;
      });
    }
  }
  return flowerList.value;
});

const loadFlowerOptions = async () => {
  try {
    const response = await getFlowerOptions();
    flowerList.value = response.map(item => ({
      title: item.name,
      value: item.id,
      avatar: () => {
        if (item.images && item.images.length > 0) {
          return h("img", {
            src: SERVER_URL + item.images[0],
            style:
              "width:128px; height:64px; object-fit:contain; display:block;"
          });
        } else {
        }
        return h("img", {
          src: "/images/flower.png",
          style: "width:128px; height:64px; object-fit:contain; display:block;"
        });
      },

      description: () => h("p", {}, `￥${item.price}`)
    }));
  } catch (error) {
    console.log(error);
  }
};

const { columns } = useColumns({
  onDelete: async (row, index) => {
    try {
      console.log(row);
      const data: {
        id: number;
        title: string;
        children: number[];
      }[] = [];

      rawData.forEach(item => {
        if (row.recommend && item.id === row.recommend.id) {
          data.push({
            id: item.id,
            title: item.title,
            children: item.children
              .filter(i => i.id !== row.id)
              .map(child => child.id)
          });
        } else {
          data.push({
            id: item.id,
            title: item.title,
            children: item.children.map(child => child.id)
          });
        }
      });

      await updateAppConfig({
        name: "weixin-home-recommend",
        data
      });

      message("删除成功", { type: "success" });
      loadData();
    } catch (e) {
      if (e.response.data && e.response.data.message) {
        message(e.response.data.message, { type: "error" });
      } else {
        message("删除失败", { type: "error" });
      }
      console.log(e);
    }
  }
});

let rawData: HomeRecommendItem[] = [];
const loadData = async () => {
  try {
    state.loading = true;
    rawData = await getWexinHomeRecommend();
    typeDataSource.value = rawData.map(item => ({
      id: item.id,
      label: item.title
    }));
    typeOptions.value = rawData.map(item => ({
      label: item.title,
      value: item.id
    }));

    const data = [];

    rawData.forEach(item => {
      item.children.forEach(child => {
        data.push({
          ...child,
          recommend: {
            id: item.id,
            title: item.title
          }
        });
      });
    });

    console.log(data);

    dataList.value = data;
    state.loading = false;
  } catch (error) {
    console.log(error);
  }
};

onMounted(async () => {
  await loadFlowerOptions();
  loadData();
});

const formRules = {
  type: [
    {
      required: true,
      message: "请选择推荐类型"
    }
  ],
  flower_id: [
    {
      required: true,
      message: "请选择鲜花"
    }
  ]
};
const formVisible = ref(false);
const formRef = ref<PlusDialogFormInstance | null>(null);
const formData = ref<FieldValues>({ status: 1 });
const formColumns: PlusColumn[] = [
  {
    label: "推荐分类",
    width: 120,
    prop: "type",
    valueType: "select",
    options: computed(() => typeOptions.value)
  },
  {
    label: "鲜花",
    prop: "flower_id",
    renderField(value: string, onChange) {
      return h(Fragment, [
        h(
          ElScrollbar,
          { height: 400 },
          h(PlusCheckCardGroup, {
            modelValue: value,
            options: flowerOptions.value,
            onChange: e => {
              onChange(e);
              nextTick(() => {
                formRef.value.formInstance.validateField(["flower_id"]);
              });
            }
          })
        )
      ]);
    }
  }
];

watch(
  () => formData.value.type,
  () => {
    formData.value.flower_id = undefined;
  }
);

const handleAdd = () => {
  formData.value = {};
  formVisible.value = true;
};

const handleConfirm = async e => {
  try {
    state.submitting = true;

    const data: {
      id: number;
      title: string;
      children: number[];
    }[] = [];

    rawData.forEach(item => {
      data.push({
        id: item.id,
        title: item.title,
        children:
          item.id === e.type
            ? [...item.children.map(child => child.id), e.flower_id]
            : item.children.map(child => child.id)
      });
    });

    await updateAppConfig({
      name: "weixin-home-recommend",
      data
    });

    message("保存成功", { type: "success" });
    formVisible.value = false;
    loadData();
  } catch (e) {
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("保存失败", { type: "error" });
    }
    console.log(e);
  } finally {
    state.submitting = false;
  }
};

const typeDataSource = ref<ElTreeItem[]>([]);
const typeFormVisible = ref(false);
const typeFormData = ref<FieldValues>({ status: 1 });
const typeFormRules = {
  title: [
    {
      required: true,
      message: "请输入标题"
    }
  ]
};
const typeFormColumns: PlusColumn[] = [
  {
    label: "标题",
    width: 120,
    prop: "title",
    valueType: "input"
  }
];

const handleNewType = () => {
  typeFormData.value = {};
  typeFormVisible.value = true;
};

const handleEditType = (e: { id: number; label: string }) => {
  typeFormData.value = { id: e.id, title: e.label };
  typeFormVisible.value = true;
};

const handleTypeConfirm = async e => {
  try {
    if (!e.id) {
      const data = [
        ...rawData.map((item, index) => ({
          id: index + 1,
          title: item.title,
          children: item.children.map(child => child.id)
        })),
        {
          id: rawData.length + 1,
          title: e.title,
          children: []
        }
      ];

      await updateAppConfig({
        name: "weixin-home-recommend",
        data: data
      });
    } else {
      const index = rawData.findIndex(item => item.id === e.id);
      rawData[index].title = e.title;
      await updateAppConfig({
        name: "weixin-home-recommend",
        data: rawData.map((item, index) => ({
          id: item.id,
          title: item.title,
          children: item.children.map(child => child.id)
        }))
      });
    }
    message("保存成功", { type: "success" });
    typeFormVisible.value = false;
    loadData();
  } catch (e) {
    console.log(e);
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("保存失败", { type: "error" });
    }
    console.log(e);
  } finally {
    state.submitting = false;
  }
};

const handleDeleteType = async e => {
  try {
    const data: {
      id: number;
      title: string;
      children: number[];
    }[] = [];

    rawData.forEach(item => {
      if (item.id !== e.id) {
        data.push({
          id: item.id,
          title: item.title,
          children: item.children.map(child => child.id)
        });
      }
    });

    await updateAppConfig({
      name: "weixin-home-recommend",
      data
    });
    loadData();
    message("保存成功", { type: "success" });
  } catch (e) {
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("保存失败", { type: "error" });
    }
    console.log(e);
  }
};
</script>
<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span>今日推荐</span>

          <el-space>
            <el-button type="primary" @click="handleAdd">
              <template #icon>
                <IconifyIconOnline icon="ep:plus" />
              </template>
              添加
            </el-button>
          </el-space>
        </div>
      </template>
      <div class="flex">
        <div
          class="w-60 shrink-0 mr-4 pb-4"
          style="border: 1px solid var(--el-border-color-lighter)"
        >
          <div class="p-4">
            <el-button type="primary" class="w-full" @click="handleNewType">
              <template #icon>
                <IconifyIconOnline icon="ep:plus" />
              </template>
              添加分类
            </el-button>
          </div>
          <el-tree
            :data="typeDataSource"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
          >
            <template #default="{ node, data }">
              <span class="flex-1 flex justify-between w-0">
                <span class="truncate">{{ node.label }}</span>
                <span class="pr-4">
                  <el-button type="primary" link @click="handleEditType(data)">
                    <IconifyIconOnline icon="ep:edit-pen" />
                  </el-button>
                  <el-popconfirm
                    title="确认删除?"
                    placement="top-end"
                    @confirm="handleDeleteType(data)"
                  >
                    <template #reference>
                      <el-button type="danger" link>
                        <IconifyIconOnline icon="ep:delete" />
                      </el-button>
                    </template>
                  </el-popconfirm>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
        <div class="flex-1 overflow-hidden">
          <pure-table
            border
            adaptive
            row-key="id"
            :loading="state.loading"
            :data="dataList"
            :columns="columns"
          />
        </div>
      </div>
    </el-card>
    <PlusDialogForm
      v-model:visible="typeFormVisible"
      v-model="typeFormData"
      :destroy-on-close="true"
      :title="typeFormData.id ? '修改' : '添加'"
      :form="{
        columns: typeFormColumns,
        rules: typeFormRules,
        labelPosition: 'top',
        rowProps: {
          gutter: 12
        }
      }"
      :confirmLoading="state.submitting"
      @confirm="handleTypeConfirm"
    />
    <PlusDialogForm
      ref="formRef"
      v-model:visible="formVisible"
      v-model="formData"
      title="添加"
      :destroy-on-close="true"
      :form="{
        columns: formColumns,
        rules: formRules,
        labelPosition: 'top',
        rowProps: {
          gutter: 12
        }
      }"
      :confirmLoading="state.submitting"
      @confirm="handleConfirm"
    />
  </div>
</template>
<style scoped lang="scss">
:deep(.swiper-upload) {
  .el-upload--picture-card {
    width: 320px;
    overflow: hidden;
  }
}
:deep(.plus-check-card) {
  padding-block: 12px;
  padding-inline: 0;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
</style>
